import { Injectable } from '@angular/core';
import { InAppBrowser } from '@ionic-native/in-app-browser';
import { StorageProvider } from "../storage/storage";
import { ConfigProvider } from "../config/config";
import { UrlProvider } from "../url/url";
import { HttpServicesProvider } from "../http-services/http-services";
import { UtilsProvider } from "../utils/utils";
import { WechatProvider } from "../wechat/wechat";

@Injectable()
export class ValidateProvider {

    constructor(
        public httpService: HttpServicesProvider,
        public browserCtrl: InAppBrowser,
        public storage: StorageProvider,
        public config: ConfigProvider,
        public url: UrlProvider,
        public util: UtilsProvider,
        public wechat: WechatProvider
    ) {

    }

    //验证用户是否登录
    checkLogin() {
        let flag = true;
        if (flag) {
            let tokenInfo = this.storage.get('tokenInfo');
            if (!tokenInfo) {
                return false;
            } else {
                tokenInfo = JSON.parse(tokenInfo);
                if (tokenInfo['timestamp'] + 3600 * 24 * 7 < this.util.getTime()) {
                    this.storage.clear();
                    location.reload();
                    return false;
                }
                tokenInfo['timestamp'] = this.util.getTime() + 3600 * 24 * 7;
                this.storage.set('tokenInfo', JSON.stringify(tokenInfo));
                // document.cookie = 'tokenInfo=' + JSON.stringify(tokenInfo);
                
                return true;
            }
        } else {
            return true;
        }
    }
    usualShare(){
        let userInfo = JSON.parse(this.storage.get('userInfo'));
        setTimeout(()=>{
            this.wechat.getWxConfig(() => {
                this.wechat.wxShareMoments({ shareNumber: 0, shareTitle: '', amoyId: 0, userId:userInfo.user_id });
                this.wechat.wxShareFriend({ shareNumber: 0, shareTitle: '', amoyId: 0 , userId:userInfo.user_id});
            });
        },1000)
    }

    checkWxInfo() {
        let flag = true;
        if (flag) {
            let wxInfo = this.storage.get('wxInfo');
            return !!wxInfo;
        } else {
            return true;
        }
    }

    //获取用户微信信息
    getWxInfo(callback) {
        if (this.storage.get('wxInfo')) {
            let wxInfo = JSON.parse(this.storage.get('wxInfo'));
            this.getToken(wxInfo['openid'], result => {
                callback(result);
            });
            return false;
        }
        if (this.url.getParam('code') && !this.storage.get('wxInfo')) {
            let code = this.url.getParam('code');
            this.httpService.requestData('/wechat/get_user_info?code=' + code, (response) => {
                if (response['code'] == 200) {
                    this.storage.set('wxInfo', JSON.stringify(response['info']));
                    this.getToken(response['info']['openid'], result => {
                        callback(result);
                    });
                    
                } else if (response['code'] == 400) {
                    location.href = this.config.webUrl;
                }
            });           
            return false;
        }
        if (!this.storage.get('wxInfo')) {
            let redirect_uri = encodeURIComponent(this.config.webUrl);            
            location.href = this.config.authUrl + '/wechat/get_user_code?password=123698745'+'&redirect_uri=' + redirect_uri;
        }
    }
    
    

    getToken(openid, callback) {
        this.httpService.requestData('/user/get_token/openid/' + openid, data => {
            if (data.code == 400) {
                callback(false);
            } else {
                let tokenInfo = {
                    token: data.token,
                    timestamp: this.util.getTime()
                };
                this.storage.set('tokenInfo', JSON.stringify(tokenInfo));
                this.getUserInfo((result) => {
                    callback(result);
                });

            }
        })
    }
    getUserInfo(callback) {
        let tokenInfo = this.storage.get('tokenInfo');
        if (tokenInfo) {
            tokenInfo = JSON.parse(tokenInfo);
            this.httpService.requestData('/user_info/index/token/' + tokenInfo['token'], data => {
                if (data['error'] == 200) {
                    this.storage.set('userInfo', JSON.stringify(data['data']['user_base']));
                    callback(true);
                } else {
                    callback(false);
                }

            });
        }
    }


    /**
     * 身份证省份验证
     * */
    checkProvince(val) {
        let pattern = /^[1-9][0-9]/;
        let provs = { 11: "北京", 12: "天津", 13: "河北", 14: "山西", 15: "内蒙古", 21: "辽宁", 22: "吉林", 23: "黑龙江 ", 31: "上海", 32: "江苏", 33: "浙江", 34: "安徽", 35: "福建", 36: "江西", 37: "山东", 41: "河南", 42: "湖北 ", 43: "湖南", 44: "广东", 45: "广西", 46: "海南", 50: "重庆", 51: "四川", 52: "贵州", 53: "云南", 54: "西藏 ", 61: "陕西", 62: "甘肃", 63: "青海", 64: "宁夏", 65: "新疆", 71: "台湾", 81: "香港", 82: "澳门" };
        if (pattern.test(val)) {
            if (provs[val]) {
                return true;
            }
        }
        return false;
    }

    /**
     * 身份证出生年月日验证
     * */
    checkDate(val) {
        let pattern = /^(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)$/;
        if (pattern.test(val)) {
            let year = val.substring(0, 4);
            let month = val.substring(4, 6);
            let date = val.substring(6, 8);
            let date2 = new Date(year + "-" + month + "-" + date);
            if (date2 && date2.getMonth() == (parseInt(month) - 1)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 身份证校验码验证
     * */
    checkCode(val) {
        let p = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
        let factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
        let parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2];
        let code = val.substring(17);
        if (p.test(val)) {
            let sum = 0;
            for (let i = 0; i < 17; i++) {
                sum += val[i] * factor[i];
            }
            if (parity[sum % 11] == code.toUpperCase()) {
                return true;
            }
        }
        return false;
    }

    /**
     * 身份证完整验证
     * */
    checkID(val) {
        if (this.checkCode(val)) {
            let date = val.substring(6, 14);
            if (this.checkDate(date)) {
                if (this.checkProvince(val.substring(0, 2))) {
                    return true;
                }
            }
        }
        return false;
    }
}
